"""
认证相关API
用户注册、登录等功能
"""

from flask import Blueprint, request, jsonify
import hashlib
from utils.database import DatabaseManager
from utils.validators import Validators

auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')
db = DatabaseManager()

def hash_password(password: str) -> str:
    """密码加密"""
    return hashlib.sha256(password.encode()).hexdigest()

@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    # 数据验证
    if not username or not password:
        return jsonify({'error': '用户名和密码为必填项'}), 400
    
    if not Validators.validate_username(username):
        return jsonify({'error': '用户名格式不正确'}), 400
    
    if not Validators.validate_password(password):
        return jsonify({'error': '密码长度至少6位'}), 400
    
    hashed_password = hash_password(password)
    
    try:
        # 检查用户是否已存在
        existing_user = db.execute_query(
            "SELECT id FROM users WHERE username = ?", (username,)
        )
        if existing_user:
            return jsonify({'error': '用户名已存在'}), 409
        
        # 创建新用户
        db.execute_update(
            "INSERT INTO users (username, password) VALUES (?, ?)",
            (username, hashed_password)
        )
        
        return jsonify({'message': '注册成功'}), 201
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'error': '用户名和密码为必填项'}), 400
    
    hashed_password = hash_password(password)
    
    try:
        user = db.execute_query(
            "SELECT id, username FROM users WHERE username = ? AND password = ?",
            (username, hashed_password)
        )
        
        if user:
            return jsonify({
                'message': '登录成功',
                'user': user[0]
            })
        else:
            return jsonify({'error': '用户名或密码错误'}), 401
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500 